package cn.xkai.exercise.a;

import java.util.Vector;

/**
 * @description: 回文链表
 * 链表中节点数目在范围[1, 105] 内
 * 0 <= Node.val <= 9
 * 自己的思路：把数据转化到数组，双指针比较;
 * 借鉴的思路：通过快慢指针找链表中点，然后反转尾部链表，重新进行一一比较
 * @author: kaixiang
 * @date: 2022/7/10
 **/
public class Solution41 {
    public boolean isPalindrome(ListNode head) {
        Vector<Integer> nums = new Vector<>();
        while (head != null) {
            nums.add(head.val);
            head = head.next;
        }
        int left = 0, right = nums.size() - 1;
        while (left <= right) {
            if (!nums.get(left++).equals(nums.get(right--))) {
                return false;
            }
        }
        return true;
    }

    public boolean isPalindromeRefer(ListNode head) {
        ListNode fast = head, slow = head;
        //通过快慢指针找到中点(妙)
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        //如果fast不为空，说明链表的长度是奇数个
        if (fast != null) {
            slow = slow.next;
        }
        //反转后半部分链表
        slow = reverse(slow);
        fast = head;
        while (slow != null) {
            //然后比较，判断节点值是否相等
            if (fast.val != slow.val)
                return false;
            fast = fast.next;
            slow = slow.next;
        }
        return true;
    }

    //反转链表
    public ListNode reverse(ListNode head) {
        ListNode prev = null;
        while (head != null) {
            ListNode next = head.next;
            head.next = prev;
            prev = head;
            head = next;
        }
        return prev;
    }

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public static void main(String[] args) {
        ListNode n5 = new ListNode(0);
        ListNode n4 = new ListNode(0, n5);
        ListNode n3 = new ListNode(3, n4);
        ListNode n2 = new ListNode(2, n3);
        ListNode n1 = new ListNode(1, n2);
        Solution41 solution41 = new Solution41();
        System.out.println(solution41.isPalindrome(n3));
    }
}
